<template>
    <div class="slide-container">
      <div class="slide" :style="{transitionDuration:durastr, transform:trans}">
        <slot />
      </div>
      <ul class="slide-index" v-if="showIndicators">
      <li v-for="(item, index) in length" :key="index" :class="{active:index===uindex}">
        <a href="javascript:;" @click="moveTo(index)">{{item}}</a>
      </li>
    </ul>
  </div>
</template>
<style lang="css" src="@/mycom/car.css"></style>
<script>
export default {
  name: 'carousel',
  // 变成了一个插件
  install(v) {
    v.component(this.name, this)
  },
  props:{
    interval:{
      type:Number,
      default:2000
    },
    duration:{
      type:Number,
      default: 300
    },
    showIndicators: {
       type:Boolean,
       default: true
    }
  },

  data() {
    return {

      TT:0, // 滑动定时器

      index:1, // 显示dom 中的第几个图片

      uindex:0, // 用户可见位置
      
      length : 0,  // 轮播图长度

      mapArr:[], // 真实位置与用户感知的映射

      durastr:'', 

      trans:'' 
    }
  },

  created() {
    // 补全滑动的项目，前后各一张
    var len = this.$slots.default.length;

    this.length = len;

    for(let m = 0; m < len;m++) {
      this.mapArr.push(m);
    }

    let {mapArr} = this;

    this.mapArr = [mapArr[len-1], ...mapArr, mapArr[0]];

    let {default:ots} = this.$slots;

    console.log('Vue Component-->', ots[0].name)

    ots[0].key = 'mmm';

    ots[len-1].key = 'nnn';

    this.$slots.default = [ots[len-1]].concat(ots).concat(ots[0])
  },

  mounted() {
    this.move(false)
  },

  methods: {
    move( ani = true) {

      let {duration, interval} = this;

      let durastr = duration/1000 + 's';

      clearTimeout(this.TT);

      // 用户感知位置
      this.durastr = ani?durastr:'';
      this.trans = `translate3D(${this.index * -520}px, 0px, 0px)`
      this.uindex = this.mapArr[this.index];

      this.index++;

      if (this.index === this.length + 2) {
        this.index = 1;
        setTimeout(() => {
          this.move(false);
        }, 300);
      }
      this.TT = setTimeout(() => {
        this.move();
      }, interval);
    },

    moveTo(i) {
      this.index = i+1;
      this.move();
    }
  }
}
</script>